<template>
  <div class="mcp-service-container">
    <!-- 搜索区域 -->
    <div class="filter-container">
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item>
          <el-input
            v-model="queryParams.keyword"
            placeholder="请输入服务名称/描述"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryParams.tag" placeholder="服务标签" clearable>
            <el-option label="网页搜索" value="网页搜索" />
            <el-option label="图像生成" value="图像生成" />
            <el-option label="生活工具" value="生活工具" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryParams.mcpType" placeholder="MCP类型" clearable>
            <el-option label="SSE" value="SSE" />
            <el-option label="Stdio" value="Stdio" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            <span>搜索</span>
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>
            <span>重置</span>
          </el-button>
        </el-form-item>
      </el-form>
      <div class="action-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          <span>新增MCP服务</span>
        </el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="loading"
      :data="serviceList"
      border
      stripe
      style="width: 100%"
      highlight-current-row
      v-if="serviceList && serviceList.length > 0"
    >
      <el-table-column label="序号" type="index" width="60" align="center" />
      <el-table-column prop="name" label="服务名称" align="center" min-width="120" show-overflow-tooltip />
      <el-table-column prop="description" label="服务描述" align="center" min-width="180" show-overflow-tooltip />
      <el-table-column label="服务标签" align="center" min-width="150" show-overflow-tooltip>
        <template #default="{ row }">
          <div class="tag-group">
            <el-tag 
              v-for="(tag, index) in row.tags ? row.tags.split(',') : []" 
              :key="index"
              size="small"
              class="mx-1"
            >
              {{ tag }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="MCP类型" align="center" min-width="120" show-overflow-tooltip>
        <template #default="{ row }">
          <div class="tag-group">
            <el-tag 
              v-for="(type, index) in row.mcpType ? row.mcpType.split(',') : []" 
              :key="index"
              type="success"
              size="small"
              class="mx-1"
            >
              {{ type }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="url" label="URL地址" align="center" min-width="220" show-overflow-tooltip />
      <el-table-column label="状态" align="center" width="100">
        <template #default="{ row }">
          <el-tag :type="row.enabled ? 'success' : 'danger'">
            {{ row.enabled ? '已启用' : '已禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" width="160" show-overflow-tooltip>
        <template #default="{ row }">
          {{ formatDate(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200">
        <template #default="{ row }">
          <el-button 
            type="primary" 
            link 
            @click="handleEdit(row)"
            size="small"
          >
            编辑
          </el-button>
          <el-button 
            v-if="!row.enabled" 
            type="success" 
            link 
            @click="handleStatusChange(row, true)"
            size="small"
          >
            启用
          </el-button>
          <el-button 
            v-else 
            type="warning" 
            link 
            @click="handleStatusChange(row, false)"
            size="small"
          >
            禁用
          </el-button>
          <el-button 
            type="danger" 
            link 
            @click="handleDelete(row)"
            size="small"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 无数据提示 -->
    <el-empty 
      v-if="!loading && (!serviceList || serviceList.length === 0)" 
      description="暂无数据"
    >
      <el-button type="primary" @click="handleAdd">添加MCP服务</el-button>
    </el-empty>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="650px"
      append-to-body
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="服务名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入服务名称" />
        </el-form-item>
        <el-form-item label="服务描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入服务描述" />
        </el-form-item>
        <el-form-item label="服务标签" prop="tags">
          <el-select
            v-model="selectedTags"
            multiple
            collapse-tags
            collapse-tags-tooltip
            placeholder="请选择服务标签"
            style="width: 100%"
          >
            <el-option label="网页搜索" value="网页搜索" />
            <el-option label="图像生成" value="图像生成" />
            <el-option label="生活工具" value="生活工具" />
          </el-select>
        </el-form-item>
        <el-form-item label="服务介绍" prop="introduction">
          <el-input 
            v-model="form.introduction" 
            type="textarea"
            :rows="3"
            placeholder="请输入服务介绍"
          />
        </el-form-item>
        <el-form-item label="工具描述" prop="toolDescription">
          <el-input 
            v-model="form.toolDescription" 
            type="textarea"
            :rows="3"
            placeholder="请输入工具描述"
          />
        </el-form-item>
        <el-form-item label="MCP类型" prop="mcpType">
          <el-checkbox-group v-model="selectedMcpTypes">
            <el-checkbox label="SSE" />
            <el-checkbox label="Stdio" />
          </el-checkbox-group>
        </el-form-item>
        <el-form-item 
          label="URL地址" 
          prop="url"
          v-if="isSseSelected"
        >
          <el-input v-model="form.url" placeholder="请输入URL地址" />
        </el-form-item>
        <el-form-item 
          label="MCP服务配置" 
          prop="serviceConfig"
          v-if="isStdioSelected"
        >
          <el-input 
            v-model="form.serviceConfig" 
            type="textarea"
            :rows="4"
            placeholder="请输入MCP服务配置（JSON格式）"
          />
        </el-form-item>
        <el-form-item label="排序号" prop="orderNum">
          <el-input-number v-model="form.orderNum" :min="0" style="width: 120px" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="form.enabled"
            :active-value="true"
            :inactive-value="false"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { Search, Plus, Refresh, Edit } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  getMcpServicePage,
  getMcpService,
  createMcpService,
  updateMcpService,
  deleteMcpService,
  updateMcpServiceStatus
} from '@/api/mcp';

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  keyword: '',
  tag: '',
  mcpType: ''
});

// 分页数据
const serviceList = ref([]);
const total = ref(0);
const loading = ref(false);

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref('');
const formRef = ref(null);
const isEdit = ref(false);

// 表单数据
const form = ref({
  id: undefined,
  name: '',
  description: '',
  tags: '',
  introduction: '',
  toolDescription: '',
  mcpType: '',
  url: '',
  serviceConfig: '',
  orderNum: 0,
  enabled: true
});

// 标签和MCP类型的多选处理
const selectedTags = ref([]);
const selectedMcpTypes = ref([]);

// 计算属性判断是否选择了特定MCP类型
const isSseSelected = computed(() => {
  return selectedMcpTypes.value.includes('SSE');
});

const isStdioSelected = computed(() => {
  return selectedMcpTypes.value.includes('Stdio');
});

// 表单校验规则
const rules = ref({
  name: [
    { required: true, message: '请输入服务名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入服务描述', trigger: 'blur' }
  ],
  url: [
    { required: computed(() => isSseSelected.value), message: '选择SSE类型时，URL必填', trigger: 'blur' }
  ],
  serviceConfig: [
    { required: computed(() => isStdioSelected.value), message: '选择Stdio类型时，MCP服务配置必填', trigger: 'blur' }
  ]
});

// 监听标签变化，同步到表单
watch(selectedTags, (newVal) => {
  form.value.tags = newVal.join(',');
}, { deep: true });

// 监听MCP类型变化，同步到表单
watch(selectedMcpTypes, (newVal) => {
  form.value.mcpType = newVal.join(',');
}, { deep: true });

// 加载数据
function loadData() {
  loading.value = true;
  getMcpServicePage(queryParams.value)
    .then(res => {
      console.log(res);
      if (res.code === 200) {
        serviceList.value = res.data.list;
        total.value = res.data.total;
      } else {
        ElMessage.error(res.msg || '查询失败');
        serviceList.value = [];
        total.value = 0;
      }
    })
    .catch(() => {
      ElMessage.error('查询失败');
      serviceList.value = [];
      total.value = 0;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 搜索
function handleSearch() {
  queryParams.value.pageNum = 1;
  loadData();
}

// 重置查询
function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    keyword: '',
    tag: '',
    mcpType: ''
  };
  loadData();
}

// 新增
function handleAdd() {
  resetForm();
  isEdit.value = false;
  dialogTitle.value = '新增MCP服务';
  dialogVisible.value = true;
}

// 编辑
function handleEdit(row) {
  resetForm();
  isEdit.value = true;
  dialogTitle.value = '编辑MCP服务';
  
  getMcpService(row.id).then(res => {
    if (res.code === 200) {
      const data = res.data;
      form.value = { ...data };
      
      // 处理标签和MCP类型
      selectedTags.value = data.tags ? data.tags.split(',') : [];
      selectedMcpTypes.value = data.mcpType ? data.mcpType.split(',') : [];
      
      dialogVisible.value = true;
    } else {
      ElMessage.error(res.msg || '获取服务信息失败');
    }
  }).catch(() => {
    ElMessage.error('获取服务信息失败');
  });
}

// 提交表单
function submitForm() {
  formRef.value.validate((valid) => {
    if (valid) {
      const submitFunc = isEdit.value ? updateMcpService : createMcpService;
      const successMsg = isEdit.value ? '修改成功' : '新增成功';
      
      submitFunc(form.value).then(res => {
        if (res.code === 200 && res.data) {
          ElMessage.success(successMsg);
          dialogVisible.value = false;
          loadData();
        } else {
          ElMessage.error(res.msg || '操作失败');
        }
      }).catch(() => {
        ElMessage.error('操作失败');
      });
    }
  });
}

// 删除
function handleDelete(row) {
  ElMessageBox.confirm(`确认删除服务 ${row.name} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteMcpService(row.id).then(res => {
      if (res.code === 200 && res.data) {
        ElMessage.success('删除成功');
        loadData();
      } else {
        ElMessage.error(res.msg || '删除失败');
      }
    }).catch(() => {
      ElMessage.error('删除失败');
    });
  }).catch(() => {});
}

// 状态变更
function handleStatusChange(row, enabled) {
  const statusText = enabled ? '启用' : '禁用';
  ElMessageBox.confirm(`确认${statusText}服务 ${row.name} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    updateMcpServiceStatus(row.id, enabled).then(res => {
      if (res.code === 200 && res.data) {
        ElMessage.success(`${statusText}成功`);
        loadData();
      } else {
        ElMessage.error(res.msg || `${statusText}失败`);
      }
    }).catch(() => {
      ElMessage.error(`${statusText}失败`);
    });
  }).catch(() => {});
}

// 页码变更
function handleCurrentChange(page) {
  queryParams.value.pageNum = page;
  loadData();
}

// 每页条数变更
function handleSizeChange(size) {
  queryParams.value.pageSize = size;
  queryParams.value.pageNum = 1;
  loadData();
}

// 重置表单
function resetForm() {
  form.value = {
    id: undefined,
    name: '',
    description: '',
    tags: '',
    introduction: '',
    toolDescription: '',
    mcpType: '',
    url: '',
    serviceConfig: '',
    orderNum: 0,
    enabled: true
  };
  selectedTags.value = [];
  selectedMcpTypes.value = [];
  
  // 延迟重置表单验证
  if (formRef.value) {
    formRef.value.resetFields();
  }
}

// 格式化日期
function formatDate(dateString) {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
}

// 页面加载时获取数据
onMounted(() => {
  loadData();
});
</script>

<style scoped>
.mcp-service-container {
  padding: 20px;
}

.filter-container {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  padding: 18px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding: 10px 0;
}

.tag-group {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.mx-1 {
  margin-left: 4px;
  margin-right: 4px;
}
</style> 